package com.mobartisan.workinglunch.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mobartisan.workinglunch.R;
import com.mobartisan.workinglunch.SnakeApplication;
import com.mobartisan.workinglunch.bean.AccountRecord;
import com.mobartisan.workinglunch.bean.globalSetting;
import com.mobartisan.workinglunch.constants.Constants;
import com.mobartisan.workinglunch.ui.base.BaseActivity;
import com.mobartisan.workinglunch.util.ObjectUtils;
import com.mobartisan.workinglunch.util.SharedPreferencesUtil;
import com.mobartisan.workinglunch.util.ToastUtils;
import com.mobartisan.workinglunch.widget.CheckVersionThread;
import com.orhanobut.logger.Logger;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import rx.Subscriber;

import static android.R.id.list;
import static com.mobartisan.workinglunch.R.id.et_money;

public class LoginActivity extends BaseActivity {

    private static final String TAG = LoginActivity.class.getSimpleName();
    @Bind(R.id.et_username)
    EditText edname;
    @Bind(R.id.et_userpassword)
    EditText edpassword;
    @Bind(R.id.bt_login)
    Button login;
    String name, password;
    Context context;
    String versionName;
    @Bind(R.id.VersionName)
    TextView VersionCode;
    globalSetting setting;
    private long firstTime = 0;
    int meswhat =-1;
    private PackageInfo info = null;
    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 2:
                    meswhat = msg.what;
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        context = this;
        SnakeApplication.loginActivity = this;
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
//                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
//
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        this.initData();
        this.initView();
    }


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void initView() {
        name = SharedPreferencesUtil.getInstance().getStringValue("username");
        password = SharedPreferencesUtil.getInstance().getStringValue("password");
        edname.setText(name);
        edpassword.setText(password);
//        if (!name.equals(""))
//            edpassword.requestFocus();
        if(Constants.isChangePassword){
            edpassword.requestFocus();
            Constants.isChangePassword=false;
        }else {
            edname.setSelection(edname.getText().length());
        }
    }

    @Override
    public void initData() {
        try {
            info = this.context.getPackageManager().getPackageInfo(this.context.getPackageName(), 0);
            VersionCode.setText(info.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (!Constants.isCheckout){
            getVersionName();
        }


    }


    public String getVersionName() {
        final String[] network_VersionName = new String[1];
        final BmobQuery<globalSetting> bmobQuery = new BmobQuery<globalSetting>();
        //bmobQuery.setLimit(2);
//        bmobQuery.order("createdAt");
//        //先判断是否有缓存
//        boolean isCache = bmobQuery.hasCachedResult(AccountRecord.class);
//        if(isCache){
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);	// 先从缓存取数据，如果没有的话，再从网络取。
//        }else{
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);	// 如果没有缓存的话，则先从网络中取
//        }
//		observable形式
        bmobQuery.findObjectsObservable(globalSetting.class)
                .subscribe(new Subscriber<List<globalSetting>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        loge(e,TAG);
                    }

                    @Override
                    public void onNext(List<globalSetting> persons) {
                        //log("查询成功：共"+persons.size()+"条数据。");
                        //ToastUtils.showShort("查询成功：共" + persons.size() + "条数据。");
                        //给数据重新排序
                        setting = persons.get(0);
                        network_VersionName[0] =setting.getCurrentversion();
                        Constants.isCheckout= true;
                        CheckVersionThread versionThread =new  CheckVersionThread(getActivity(),setting,null);
                        versionThread.compareVersionCode();

                    }
                });
//		bmobQuery.findObjects(new FindListener<Person>() {
//
//			@Override
//			public void done(List<Person> object, BmobException e) {
//				if(e==null){
//					toast("查询成功：共"+object.size()+"条数据。");
//					for (Person person : object) {
//						Log.d(TAG, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ");
//						Log.d(TAG, "ObjectId = "+person.getObjectId());
//						Log.d(TAG, "Name = "+person.getName());
//						Log.d(TAG, "Age = "+person.getAge());
//						Log.d(TAG, "Address = "+person.getAddress());
//						Log.d(TAG, "Gender = "+person.isGender());
//						Log.d(TAG, "CreatedAt = "+person.getCreatedAt());
//						Log.d(TAG, "UpdatedAt = "+person.getUpdatedAt());
//					}
//				}else{
//					loge(e);
//				}
//			}
//		});
        return network_VersionName[0];
    }

    @OnClick(R.id.bt_login)
    public void click(View view) {
        name = edname.getText().toString();
        password = edpassword.getText().toString();
        if (ObjectUtils.isStringEmpty(name) || ObjectUtils.isStringEmpty(password)) {
            ToastUtils.showShort("请正确输入用户名密码");
        } else {
            testLogin();
        }

    }

    /**
     * 注意下如果返回206错误 一般是多设备登录导致
     */
    private void testLogin() {
        final BmobUser user = new BmobUser();
        user.setUsername(name);
        user.setPassword(password);
        //login回调
        /*user.login(new SaveListener<BmobUser>() {

			@Override
			public void done(BmobUser bmobUser, BmobException e) {
				if(e==null){
					toast(user.getUsername() + "登陆成功");
					testGetCurrentUser();
				}else{
					loge(e);
				}
			}
		});*/
        //v3.5.0开始新增加的rx风格的Api
        user.loginObservable(BmobUser.class).subscribe(new Subscriber<BmobUser>() {
            @Override
            public void onCompleted() {
                log("----onCompleted----",TAG);
            }

            @Override
            public void onError(Throwable e) {
                Throwable e1 = new BmobException(e);
                if (((BmobException) e1).getErrorCode() == Constants.Network_Error_Code) {
                    ToastUtils.showShort("登录失败,请检查您的网络");
                } else if (((BmobException) e1).getErrorCode() == Constants.Network_Timeout_Code) {
                    ToastUtils.showShort("网络超时");
                } else if (((BmobException) e1).getErrorCode() == Constants.Login_Error_Code) {
                    ToastUtils.showShort("用户名或密码不正确");
                } else if (((BmobException) e1).getErrorCode() == Constants.more_Login_Error_Code) {
                    ToastUtils.showShort("您的账号在多个设备登录");
                }

                loge(new BmobException(e),TAG);
            }

            @Override
            public void onNext(BmobUser bmobUser) {
                ToastUtils.showShort("登录成功");
                SharedPreferencesUtil.getInstance().setStringValue("username", name);
                SharedPreferencesUtil.getInstance().setStringValue("password", password);
                //testGetCurrentUser();
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra("meswhat",meswhat);
                startActivity(intent);
                finish();
            }
        });
    }
    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            Toast.makeText(LoginActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            firstTime = secondTime;
        } else {
            SnakeApplication.getInstance().exitApp();
        }
    }
}
